package com.pay.game.central.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pay.game.central.common.Result;
import com.pay.game.central.common.ResultGenerator;
import com.pay.game.central.security.annotaion.UserLoginToken;
import com.pay.game.central.system.bean.Role;
import com.pay.game.central.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @PostMapping
    @ResponseBody
    @UserLoginToken
    Result<String> addRole(@RequestBody String body){
        JSONObject jsonObject = JSON.parseObject(body);
        String name = jsonObject.getString("name");
        String detail = jsonObject.getString("detail");
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(detail)){
            return ResultGenerator.genFailResult("name,detail都不能为空");
        }
        if (!StringUtils.isEmpty(name) && null==roleService.getRoleByName(name)){
            roleService.addRole(name, detail);
            return ResultGenerator.genSuccessResult("添加成功");
        }else {
            return ResultGenerator.genFailResult("角色名重复");
        }
    }

    @GetMapping("/list")
    @UserLoginToken
    @ResponseBody
    Result<PageInfo<Role>> list(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "20") int limit, String name){
        PageHelper.startPage(page,limit);
        return ResultGenerator.genSuccessResult(new PageInfo<>(roleService.list(name)));
    }

    @DeleteMapping("/{id}")
    @UserLoginToken
    @ResponseBody
    Result<String> delete(@PathVariable int id){
        roleService.deleteRole(id);
        return ResultGenerator.genSuccessResult("权限删除成功");
    }

}
